package cn.edu.hbpu.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author lcy
 * @date 2022/8/4 7:46
 * @description
 */
public class JwtUtils {

    /**
     * 设置有效期为 7 天
     */
    private static final long JWT_TTL = 60 * 60 * 1000 * 24 * 7L;
    /**
     * 设置秘钥明文
     */
    private static final String JWT_KEY = "lcy";

    public static void main(String[] args) {
        //String jwt = createJwt("1", 1000 * 60 * 60L);
        //System.out.println(jwt);
        Claims claims = parseJwt("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiNGU5ZDE5ZWMzMzM0OThkOGI4NDY0NmY1OWI3NjhjYiIsInN1YiI6IjE1NTY1NTcyNTYxODMwMzM4NTciLCJpc3MiOiJsY3kiLCJpYXQiOjE2NjAwMTg2MTEsImV4cCI6MTY2MDYyMzQxMX0.nt_P40ZXjKGaSIOHMpAYLGUDj8t1v1S85Bqnw3XWN0I");
        System.out.println(claims.getExpiration());
        System.out.println(claims.getSubject());
    }

    /**
     * @return 生成去掉 - 的UUID并返回
     */
    public static String getUuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtils.JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = JwtUtils.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                //唯一的ID
                .setId(uuid)
                // 主题  可以是JSON数据
                .setSubject(subject)
                // 签发者
                .setIssuer("lcy")
                // 签发时间
                .setIssuedAt(now)
                //使用HS256对称加密算法签名, 第二个参数为秘钥
                .signWith(signatureAlgorithm, secretKey)
                .setExpiration(expDate);
    }

    /**
     * 生成jwt并返回
     *
     * @param subject token中要存放的数据（json格式）
     * @return token字符串
     */
    public static String createJwt(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUuid());
        return builder.compact();
    }

    /**
     * 生成jtw
     *
     * @param subject   token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return token字符串
     */
    public static String createJwt(String subject, Long ttlMillis) {
        // 设置过期时间
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUuid());
        return builder.compact();
    }

    /**
     * 解析jwt并返回
     *
     * @param jwt 要解析的token字符串
     * @return 解析后的结果
     */
    public static Claims parseJwt(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * 判断 token 是否过期
     * @param claims
     * @return
     */
    public boolean isJwtExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
